﻿//===============================================================================
// Apolineo Patterns & Practices LeanEngine Framework
//===============================================================================
// Copyright © Apolineo Desenvolvimento de Sistemas Ltda.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================

using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;
using LeanEngine.Extensions;
using LeanEngine.Entity;
using LeanEngine.Collections;
using LeanEngine.SalesConcept.Entity;
using System.Globalization;

namespace LeanEngine.SalesConcept.Windows.Control
{
    public partial class MaintenanceControlOfSaleDetail : UserControl
    {
        [Category("Behavior")]
        [Description("Fired when a new product has been successfuly added to the sold products list.")]
        public event Action<decimal> TotalSoldUpdated;

        public MaintenanceControlOfSaleDetail()
        {
            InitializeComponent();

            this.selProduct.FormSelect = new FormSelectProduct();
            this.dataGridView1.AutoGenerateColumns = false;
        }
        
        private ChangeTrackerCollection<SaleDetail> _soldProductsList;

        [Browsable(false)]
        public ChangeTrackerCollection<SaleDetail> SoldProductsList 
        {
            get { return this._soldProductsList; }
            set
            {
                dataGridView1.DataSource = null;
                if (value.IsNull())
                {
                    _soldProductsList = new ChangeTrackerCollection<SaleDetail>();                    
                }
                else
                {
                    _soldProductsList = value;
                    dataGridView1.DataSource = this._soldProductsList;
                }
            }
        }

        [Browsable(false)]
        public bool PerformValidationEnabled
        {
            get { return this.propertyValidatorProvider1.Enabled; }
            set { this.propertyValidatorProvider1.Enabled = value; }
        }

        private SaleDetail GetControlsValues()
        {
            var value = new SaleDetail()
            {
                Price = this.txtPrice.Text.Trim().ToDecimal(),
                Discount = this.txtDiscount.Text.IsNullOrEmpty() ? 0 : this.txtDiscount.Text.Trim().ToDecimal(),
                Quantity = this.txtQuantity.Value.ToInt32(),
                Product = (Product)this.selProduct.SelectedValue
            };

            return value;
        }

        private void SetControlsValues(int index)
        {
            this.txtPrice.Text = this.SoldProductsList[index].Price.ToString();
            this.txtDiscount.Text = this.SoldProductsList[index].Discount.ToString();
            this.txtQuantity.Value = this.SoldProductsList[index].Quantity;
            this.selProduct.SelectedValue = this.SoldProductsList[index].Product;

            this.selProduct.Focus();
        }

        private void ClearControlsValues()
        {
            this.txtPrice.Text = "0";
            this.txtDiscount.Text = string.Empty;
            this.txtQuantity.Value = this.txtQuantity.Minimum;
            this.selProduct.SelectedValue = null;

            this.selProduct.Focus();
        }

        private void OnTotalSoldUpdated()
        {
            var totalSold = (from d in this.SoldProductsList
                             select new { Total = d.Price * d.Quantity }).Sum(item => item.Total);
            if (this.TotalSoldUpdated.IsNotNull())
            {
                this.TotalSoldUpdated.Invoke(totalSold);
            }
        }

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if (e.RowIndex.IsGreaterThanEqual(0) &&
                    this.SoldProductsList.Count > e.RowIndex)
                {
                    SetControlsValues(e.RowIndex);
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                if ((e.KeyCode == Keys.Delete || e.KeyValue == 46) && dataGridView1.SelectedCells.Count.IsGreaterThan(0))
                {
                    var index = dataGridView1.SelectedCells[0].RowIndex;
                    if (this.SoldProductsList.Count.IsGreaterThan(index))
                    {
                        this.SoldProductsList.RemoveAt(index);
                        this.dataGridView1.DataSource = null;
                        this.dataGridView1.DataSource = this.SoldProductsList;
                        OnTotalSoldUpdated();
                    }
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                this.PerformValidationEnabled = true;
                if (this.ValidateChildren(ValidationConstraints.ImmediateChildren))
                {
                    var productSold = GetControlsValues();
                    this.SoldProductsList.Add(productSold);
                    this.dataGridView1.DataSource = null;
                    this.dataGridView1.DataSource = this.SoldProductsList;
                    ClearControlsValues();
                    OnTotalSoldUpdated();
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                ClearControlsValues();
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
    }
}
